package process;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

import android.widget.ProgressBar;

public class SendFileUDP {
	private int m_port = 8282;
	private String m_Start = "SendFileName";
	
	String[]g_ArrayOfIP;
	SendAllFile send = new SendAllFile();
	
	public int sendDuongDanFile(String host, int port,String thongtin) 
	{
		int kt = 0;
		DatagramSocket socket = null;
		DatagramPacket data ;
		try {

			InetAddress IA = InetAddress.getByName(host);
			data = new DatagramPacket(thongtin.getBytes(), thongtin.length(), IA, port);
			socket = new DatagramSocket();
			socket.send(data);
			kt = 1;
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		socket.close();
		return kt;
		
		
		
	}
	public int  sendThongTin(String host, int port,String thongtin) 
	{
		int kt = 0;
		DatagramSocket socket = null;
		DatagramPacket data ;
		try {

			InetAddress IA = InetAddress.getByName(host);
			data = new DatagramPacket(thongtin.getBytes(), thongtin.length(), IA, port);
			socket = new DatagramSocket();
			socket.send(data);
			kt = 1;
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		socket.close();
		return kt;
	}

public String SendUsingUDP(ProgressBar pB,String m_Path ,String m_filename,String[] ArrayOfIP)
{
	
	String thongbao ="";
	SendAllFile send = new SendAllFile();
	for(int i=0;i<ArrayOfIP.length;i++)
	{
		
		String m_host=ArrayOfIP[i];
		int kq = send.SendInfoStartSendUDP(m_host, m_port, m_Start);
		
		if(kq==1)
		{
			 int ports = 8181;
			 int kq1 = send.sendfilename(m_host, ports, m_filename);
			// int kq1 = send.SendfilenameUDP(m_host, ports, m_filename);
				if(kq1!=0)
				{
					int portss = 8383;
					int kq3 = send.SenContentFile(pB,m_Path, m_filename, m_host, portss);
					thongbao = "successful";
					
				}
				else
				{
					thongbao = "unsuccessful";
				}
		}
	}
	return thongbao;
	
	}
}


